package com.nervenets.web.controller.handler.user.user;

import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.AuthStatus;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.redis.utils.ISyncExecutor;

import javax.servlet.http.HttpServletRequest;

public class UserAuthHandler extends Handler<UserAuthParams> {
    @Override
    public String handle(UserAuthParams params, HttpServletRequest request) throws Exception {
        return (String) redisSyncLocker.idLock(params.getUserId(), o -> {
            final User user = userDao.findById(params.getUserId(), User.class);
            if (null == user) return errorMessage(MessageCode.code_777);

            user.setAreaId(params.getAreaId());
            user.setAuthStatus(AuthStatus.checking);
            user.getInfo().setName(params.getName());
            user.getInfo().setIdNumber(params.getIdNumber());
            user.getInfo().setFrontOfId(params.getFrontOfId());
            user.getInfo().setBackOfId(params.getBackOfId());
            user.setAuthTime(0);
            userDao.saveOrUpdate(user);

            globalService.clearRedisUserStored(user.getId());

            return successMessage();
        });
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
